export const useAuth = () => {
  const checkTokenValidity = async () => {
    const token = localStorage.getItem('userToken')

    if (!token) {
      return false
    }

    // 检查token格式，Laravel Sanctum tokens通常以数字开头
    if (token === 'test-token-123456' || !token.includes('|')) {
      // 清除无效token
      localStorage.removeItem('userToken')
      localStorage.removeItem('userInfo')
      return false
    }

    return true
  }

  const requireAuth = async () => {
    const isValid = await checkTokenValidity()

    if (!isValid) {
      const currentPath = window.location.pathname
      await navigateTo(`/login?redirect=${encodeURIComponent(currentPath)}`)
      return false
    }

    return true
  }

  const logout = async () => {
    localStorage.removeItem('userToken')
    localStorage.removeItem('userInfo')
    await navigateTo('/login')
  }

  return {
    checkTokenValidity,
    requireAuth,
    logout
  }
}